package belf.migrate.api.sink.jdbc.helper;

import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据同步时，不能频繁地生成新的PreparedStatement对象，否则目标数据库的句柄会被占用完。
 * 同步数据时，对每个表缓存其PreparedStatement对象，方便重复使用；同步完成，清空缓存
 */
public class PrepareStatementCache {
    private static PrepareStatementCache instance = new PrepareStatementCache();

    private Map<String, PreparedStatement> preparedStatementMap = new HashMap<>();

    private PrepareStatementCache() {
    }

    public static PrepareStatementCache getInstance() {
        return instance;
    }

    public void add(String jobId, String database, String table, String operation, PreparedStatement preparedStatement) {
        String key = makeKey(jobId, database, table, operation);
        preparedStatementMap.put(key, preparedStatement);
    }

    public PreparedStatement get(String jobId, String database, String table, String operation) {
        String key = makeKey(jobId, database, table, operation);
        return preparedStatementMap.get(key);
    }

    public void remove(String jobId, String database, String table, String operation) {
        String key = makeKey(jobId, database, table, operation);
        preparedStatementMap.remove(key);
    }

    public void clear() {
        preparedStatementMap.clear();
    }

    private String makeKey(String jobId, String database, String table, String operation) {
        return jobId + "-" + database + "." + table + "-" + operation;
    }


}
